package com.vancouver.knows.business.tracker;

import com.pangu.bean.PageableResult;
import com.pangu.task.IResultReceiver;
import com.pangu.task.OperateResult;
import com.pangu.task.mark.ATaskMark;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.CategoryInfo;
import com.vancouver.knows.business.bean.UserPostInfo;
import com.vancouver.knows.business.cache.UserPostInfoCache;
import com.vancouver.knows.business.service.impl.FetchUserPostsHandler;
import com.vancouver.knows.business.task.mark.FetchUserPostsTaskMark;

import java.util.List;
import java.util.Map;

/**
 * Created by Chris Li on 2016-07-12.
 */
public class FetchUserPostsTracker extends ABInvokeTracker {

    public FetchUserPostsTracker(BusinessModule module, IResultReceiver resultReceiver) {
        super(module, resultReceiver);
    }

    @Override
    public String TAG() {
        return FetchUserPostsTracker.class.getSimpleName();
    }

    @Override
    protected void handleTaskRefresh(ATaskMark taskMark, OperateResult result) {
        UserPostInfoCache userPostInfoCache = module.getCacheManager().getUserPostsInfoCache();
        userPostInfoCache.deleteItemInfoIndexFromCache(taskMark);
    }


    @Override
    public void handleResult(OperateResult result) {
        PageableResult pageableResult = (PageableResult) result.getResultData();
        if (pageableResult.getContent() != null) {
            FetchUserPostsTaskMark aTaskMark = (FetchUserPostsTaskMark) result.getTaskMark();
            Map<String, Object> map = (Map<String, Object>) pageableResult.getContent();
            List<UserPostInfo> newUserPostInfo = (List<UserPostInfo>) map.get(FetchUserPostsHandler.KEY_POSTS);
            aTaskMark.setPageInfo(pageableResult.getPageInfo());
            module.getCacheManager().getUserPostsInfoCache().addItemInfoToCache(aTaskMark, newUserPostInfo);
            module.getCacheManager().setUserPostTopCategories((List<CategoryInfo>) map.get(FetchUserPostsHandler.KEY_TOP_CATEGORIES));
        }
    }
}
